import { AxiosHeaders, AxiosResponseHeaders, RawAxiosResponseHeaders } from "axios";

export namespace ContentType {
  export type Data = {
    type: string;
    parameters: { [key: string]: string | undefined; };
  };
  export async function parse(headersOrRawStr: string | RawAxiosResponseHeaders | AxiosResponseHeaders): Promise<Data> {
    const rawStr = typeof headersOrRawStr === 'string' ?
      headersOrRawStr :
      headersOrRawStr instanceof AxiosHeaders ?
        headersOrRawStr.get('content-type') :
        headersOrRawStr['content-type'];
    const ret: Data = {
      type: '',
      parameters: {}
    };
    if (typeof rawStr === 'string') {
      const parts = rawStr.split(';')
        .map(v => v.trim())
        .filter(v => v);
      ret.type = parts[0];
      const len = parts.length;
      for (let i = 1; i < len; ++i) {
        const result = parts[i].match(/(.*?)=(.*?)$/);
        if (!result) { continue; }
        ret.parameters[result[1]] = result[2];
      }
    }
    return ret;
  }
}
